import https from 'node:https'

import fs from 'node:fs'
import { fileURLToPath, URL } from 'node:url'
import path from 'node:path'

console.log(import.meta.url);


// 当前运行目录
const dir = fileURLToPath(new URL('./', import.meta.url))

const key = fs.readFileSync(path.resolve(dir, 'server.key'))
const cert = fs.readFileSync(path.resolve(dir, 'server.crt'))


/**
 * @type {https.RequestOptions}
 */
const options = {
  key: key,
  cert: cert
}

const server = https.createServer(options, (req, res) => {
  console.log('请求地址：', req.url, req.method);

  if (req.url === '/favicon.icon') {
    res.end()
    return
  }

  if (req.url === '/') {
    res.setHeader('Content-Type', 'text/html;charset=UTF8')
    res.write(`
      <div>
        <h3>你好 https</h3>

        <img src='/api/getInfo'/>
      </div>
    `)

    res.end()

    return
  }

  // 写一个https的 get请求的接口
  if(req.url === '/api/getInfo' && req.method === 'GET') {
    res.setHeader('Content-Type', 'application/json')
    res.statusCode = 200

    let content = {
      name: "张三",
      age: 12
    }

    res.write(JSON.stringify(content))
    res.end()
    return
  }
  console.log('命中');
  res.end()
})

server.on('error', (err) => {
  console.log('发生错误');
  console.log(err);
})

server.listen(443, () => {
  console.log(`启动https服务， https://localhost`);
})